package com.qiqi.ctbluetooth.util

import android.graphics.Color
import com.blankj.utilcode.util.LogUtils
import com.qiqi.ctbluetooth.UserDataLocal
import com.qiqi.ctbluetooth.data.ColorData
import java.text.DecimalFormat
import kotlin.math.log10

class Utils {
    companion object{
        /**
         *  将一个整数拆分为高八位和低八位，并转换为 16 进制字符串
         *  @param value 整数值
         *  @return Pair<String, String> 高八位和低八位的16进制字符串
         * */
         fun splitIntoHexBytes(value: Int): Pair<String, String> {
            // 计算高八位和低八位
            val highByte = (value ushr 8) and 0xFF
            val lowByte = value and 0xFF

            // 将高八位和低八位转换为 16 进制字符串，并添加前缀 "0x"
            val highByteHex = highByte.toString(16).padStart(2, '0')
            val lowByteHex = lowByte.toString(16).padStart(2, '0')

            return Pair(highByteHex, lowByteHex)
        }

        fun combineHexBytesToInt(highByteHex: String, lowByteHex: String): Int {
//            LogUtils.eTag("powerValue", "highByteHex:$highByteHex,lowByteHex:$lowByteHex")
            // 将高八位和低八位的16进制字符串转换为整数
            val highByte = highByteHex.toInt(16)
            val lowByte = lowByteHex.toInt(16)

            // 将高八位和低八位组合成一个整数
            val combinedValue = (highByte shl 8) or lowByte

            return combinedValue
        }

        fun getPower(value: Int):Int{
            val ss = (((1969-value.toFloat())/432)*100).toInt()
//            LogUtils.eTag("power", "Input:$value  Output:$ss")
            return ss
        }


        fun getDBValue(value: Double,dacValue:Double): String {
            var db = 20*( log10(value) - log10(dacValue))
            //  保留一位小数
            val df = DecimalFormat("#.0")

            return if (db > 0){
                  "+${df.format(db)}"
            }else{
                df.format(db)
            }
        }


        /**
         * 计算水平
         * @param key x轴坐标
         * @param lc 量程
         * @param sinb 特殊比值
         * @param f 前沿
         * */
        fun mathHorizontal(key: Float, lc :Int, sinb :Double, f :Double):Double{
//            LogUtils.eTag("水平","key:$key,lc:$lc,sinb:$sinb,f:$f")
            return (key / 500 * lc * sinb ) - f
        }
        /**
         * 计算深度
         * @param key x轴坐标
         * @param lc 量程
         * @param logb 特殊比值
         * */
        fun mathDepth(key: Float, lc :Int, logb :Double):Double{
//            LogUtils.eTag("深度","key:$key,lc:$lc,logb:$logb")
            return key / 500 * lc * logb
        }

        /**
         * 计算声程
         * @param key x轴坐标
         * @param lc 量程
         * */
        fun mathSound(key: Float, lc :Int):Double{
//            LogUtils.eTag("声程","key:$key,lc:$lc")
            return (key / 500 * lc).toDouble()
        }

        fun toZeroString(value :Double):String{
            var newValue = value.toInt()
            if (newValue.toString().length == 3){
                return "${newValue}"
            }else{
                return "${newValue.toString().padStart(3, '0')}"
            }
        }
        /**
         * 计算波幅
         * @param key x轴坐标
         * */
        fun mathAmplitude(key: Float):Double{
//            LogUtils.eTag("波幅","key:$key")
            return (key / 254).toDouble()
        }

        fun formatDuration(totalSeconds: Int): String {
            val hours = totalSeconds / 3600
            val minutes = (totalSeconds % 3600) / 60
            val seconds = totalSeconds % 60

            return String.format("%02d:%02d:%02d", hours, minutes, seconds)
        }

        fun getBgColorList(): MutableList<ColorData>{
            return mutableListOf(
                ColorData("黑色", Color.BLACK),
                ColorData("白色", Color.WHITE)
            )
        }
        fun getWaveformColorList(): MutableList<ColorData>{
            return mutableListOf(
                ColorData("绿色", Color.GREEN),
                ColorData("红色", Color.RED),
                ColorData("蓝色", Color.BLUE),
                ColorData("黄色", Color.YELLOW),
                ColorData("青色", Color.CYAN),
                ColorData("粉色", Color.MAGENTA),
                ColorData("反色", Color.BLACK),
            )
        }

        fun getSteppingData() = listOf(0.1f,0.5f,2f,6f)

        fun getBuffStr():String{

            var buff = (800 - UserDataLocal.globalBuff.toFloat())/10
            return "衰减:${buff}dB"
        }

        fun toZero(value: Int): String{
            return if (value < 10){
                "0$value"
            }else{
                "$value"
            }
        }


         fun getFanValue(value: Int): Int {

            return when (value){
                Color.BLACK, Color.WHITE ->{
                    LogUtils.eTag("getFanValue","value:$value")
                    if (UserDataLocal.colorBg == Color.BLACK) {
                        LogUtils.eTag("getFanValue","白")
                        Color.WHITE
                    }else{
                        LogUtils.eTag("getFanValue","黑")
                        Color.BLACK
                    }
                }
                else -> value
            }
         }


        fun evpBytesToKey(pass: ByteArray, salt: ByteArray, keyLen: Int = 32, ivLen: Int = 16): Pair<ByteArray, ByteArray> {
            val md = java.security.MessageDigest.getInstance("MD5")
            var prev: ByteArray? = null
            val out = java.io.ByteArrayOutputStream()
            while (out.size() < keyLen + ivLen) {
                md.reset()
                if (prev != null) md.update(prev)
                md.update(pass)
                md.update(salt)
                prev = md.digest()
                out.write(prev)
            }
            val buf = out.toByteArray()
            val key = buf.copyOfRange(0, keyLen)
            val iv = buf.copyOfRange(keyLen, keyLen + ivLen)
            return Pair(key, iv)
        }

        // ... existing code ...
        fun decryptAES(cipherB64: String, password: String = "CT31609"): String = try {
            // 解析 Base64，并校验 "Salted__" 前缀
            val all = android.util.Base64.decode(cipherB64, android.util.Base64.DEFAULT)
            if (all.size >= 16 && String(all, 0, 8, Charsets.US_ASCII) == "Salted__") {
                val salt = all.copyOfRange(8, 16)
                val enc = all.copyOfRange(16, all.size)

                // 由密码+salt 派生 key/iv，使用 AES/CBC/PKCS5Padding 解密
                val (key, iv) = evpBytesToKey(password.toByteArray(Charsets.UTF_8), salt)
                val plainBytes = com.blankj.utilcode.util.EncryptUtils.decryptAES(enc, key, "AES/CBC/PKCS5Padding", iv)
                plainBytes?.let { String(it, Charsets.UTF_8) } ?: ""
            } else {
                LogUtils.e("解密失败: 非 OpenSSL Salted__ 格式")
                ""
            }
        } catch (e: Exception) {
            LogUtils.e("解密失败: ${e.message}")
            ""
        }

        fun isValidDateTime(time: String?): Boolean {
            if (time.isNullOrBlank()) return false
            return try {
                val sdf = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault())
                sdf.isLenient = false
                sdf.parse(time)
                true
            } catch (e: java.text.ParseException) {
                false
            }
        }

    }
}